package is.ru.honn.rumblr.process;

import is.ru.honn.rumblr.domain.RumblrLog;
import is.ru.honn.rumblr.domain.RumblrPost;
import is.ru.honn.rumblr.domain.User;
import is.ru.honn.rumblr.http.RumblrHttpReader;
import is.ru.honn.rumblr.service.PostService;
import is.ruframework.process.RuAbstractProcess;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.util.Collection;
import java.util.List;

public class ImportTumblrProcess extends RuAbstractProcess
{
  protected RumblrLog log;
  ApplicationContext ctx;
  PostService postService;
  User user = new User();

  @Override
  public void startProcess()
  {
    RumblrHttpReader reader = new RumblrHttpReader();
    log = reader.read();
    user.setName(log.getTitle());
    user.setUsername(log.getName());
    List<RumblrPost> posts = log.getPosts();

    for (RumblrPost tpost : posts)
    {
      postService.addPost(tpost);
    }
  }

  @Override
  public void beforeProcess()
  {
    ctx =  new FileSystemXmlApplicationContext("applicationContext.xml");
    postService = (PostService)ctx.getBean("postService");
  }

  @Override
  public void afterProcess()
  {
    System.out.println("Name: " + user.getName() + " ");
    System.out.println("Username: " + user.getUsername());

    Collection<RumblrPost> posts = postService.getPosts("ru-honn");

    for (RumblrPost post : posts)
    {
      System.out.println(post.render());
    }
    postService.printSummary();
  }
}
